package ar.com.solidussource.howmuchmobile.services;

import ar.com.solidussource.howmuchmobile.common.entities.Product;
import ar.com.solidussource.howmuchmobile.common.exception.ServiceException;
import ar.com.solidussource.howmuchmobile.services.helper.RestServiceHelper;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: FT31270775
 * Date: 07/11/12
 * Time: 16:17
 * To change this template use File | Settings | File Templates.
 */
public class ProductRestService implements RestService {
    private static String SERVICE_ENDPOINT = SERVER_ENDPOINT+"/product";
    private static String OP_LIST_ENDPOINT = SERVICE_ENDPOINT+"/list.json";

    public List<Product> getProducts(Integer productSubCategoryId, Integer pageNumber, Integer size) throws ServiceException {
        List<Product> products = new ArrayList<Product>();

        HttpClient httpClient = new DefaultHttpClient();

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("productSubCategoryId", productSubCategoryId);
        params.put("pageNumber", pageNumber);
        params.put("size", size);

        String url = RestServiceHelper.addParamToUrl(OP_LIST_ENDPOINT, params);

        HttpGet get = new HttpGet(url);

        try{
            HttpResponse resp = httpClient.execute(get);
            String respStr = EntityUtils.toString(resp.getEntity());

            JSONArray respJSON = new JSONArray(respStr);

            for(int i=0; i<respJSON.length(); i++) {
                JSONObject productJSON = respJSON.getJSONObject(i);

                Product product = new Product();
                product.setId(Integer.valueOf(productJSON.getInt("id")));
                product.setName(productJSON.getString("name"));
                product.setDescription(productJSON.getString("description"));

                products.add(product);
            }

        } catch (Exception e) {
            throw new ServiceException(e);
        }

        return products;
    }

    public Product[] getProductsAsArray(Integer productSubCategoryId, Integer pageNumber, Integer size) throws ServiceException {
        List<Product> products = getProducts(productSubCategoryId, pageNumber, size);

        Product[] productsAsArray = new Product[products.size()];

        int i = 0;

        Iterator<Product> ite = products.iterator();

        while (ite.hasNext()) {
            Product product = ite.next();
            productsAsArray[i] = product;
            i++;
        }

        return productsAsArray;
    }
}
